package com.gaff.emp.core.util;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;
import org.apache.commons.io.IOUtils;

import java.io.*;

public class ZipUtil {

    public static boolean containsFile(byte[] data, String fileName) throws IOException {
        ZipArchiveInputStream in = new ZipArchiveInputStream(new ByteArrayInputStream(data));
        ZipArchiveEntry entry;
        while ((entry = in.getNextZipEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }
            if (entry.getName().equalsIgnoreCase(fileName)) {
                return true;
            }
        }
        in.close();
        return false;
    }

    public static void unzip(String zipPath, String destPath) throws IOException {
        ZipArchiveInputStream in = new ZipArchiveInputStream(new BufferedInputStream(new FileInputStream(zipPath)));
        File pathFile = new File(destPath);
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        ZipArchiveEntry entry;
        while ((entry = in.getNextZipEntry()) != null) {
            if (entry.isDirectory()) {
                File directory = new File(destPath, entry.getName());
                directory.mkdirs();
            } else {
                OutputStream os = null;
                try {
                    os = new BufferedOutputStream(new FileOutputStream(new File(destPath, entry.getName())));
                    IOUtils.copy(in, os);
                } finally {
                    IOUtils.closeQuietly(os);
                }
            }
        }
        IOUtils.closeQuietly(in);
    }

}
